//
//  ViewController.m
//  MPTLive
//
//  Created by Jeakin on 8/12/15.
//  Copyright © 2015 Jeakin. All rights reserved.
//

#import "MPTLiveViewController.h"
#import "Reachability.h"
#import "MPTLogger.h"
#import "MPTChannelModel.h"

#import <CoreTelephony/CTTelephonyNetworkInfo.h> /// 通讯类
#import <CoreTelephony/CTCarrier.h>

#import <Masonry.h>
#import <MPTLoginApp.h>
#import <JLRoutes.h>
#import "MPTHttpClient.h"
#import "MBProgressHUD.h"
#import "MPTTips.h"
// 融云sdk
#import <RongIMLib/RongIMLib.h>
#import "MPTLiveWeiboAutoShare.h"
#import <SDWebImage/UIImageView+WebCache.h>
#import <MPTVideoKit/MPTVBPixelController.h>
#import <MPTVideoKit/YXVideoEffectModel.h>
#import <YXVideoEffect.h>

#import <mach/mach_time.h>
// 准备直播vc
#import "MPTReadyLiveView.h"
// 控制view，包括控制闪光灯、摄像头翻转等等
#import "MPTControlView.h"
// 调试view，包括调试摄像头，调整自己的位置等等
#import "MPTDebugLiveView.h"
// 倒计时view，5、4、3、2、1倒计时页面
#import "MPTLiveCountDownView.h"
// 直播结束view
#import "MPTLiveOverView.h"
// 直播登录view
#import "MPTLiveLoginView.h"
// 申请内测资格view
#import "MPTLiveApplyView.h"
// 申请内测资格页面结果view
#import "MPTLiveApplyResultView.h"
// 个人中心vc
#import "MPTMeViewController.h"
//
#import "MPTLiveIMActionView.h"
//
#import "MPTLiveGuideViewController.h"
//
#import "UIDevice+Hardware.h"

#import "MPTConfig.h"

#import "MPTLiveAllUserInfoView.h"

#import "MPTLiveIMManager.h"

#import "MPTLiveShareView.h"

#import "MPTLiveKongZhiTaiView.h"/// 控制台view

const char *stateNames[] = {
    "Unknow",
    "Connecting",
    "Connected",
    "Disconnected",
    "Error"
};

const char *networkStatus[] = {
    "Not Reachable",
    "Reachable via WiFi",
    "Reachable via CELL"
};


typedef enum
{
    // 从准备直播视频view中点击开始直播按钮
    From_Ready = 0,
    // 从直播结束view上点击继续直播按钮
    From_LiveOver
}CreateVideoType;


@interface MPTLiveViewController () <PLCameraStreamingSessionDelegate,MPTLiveCountdownDelegate, PLStreamingSendingBufferDelegate>

// 是否开启前置摄像头
@property (nonatomic) BOOL cameraIsSelf;
// scid
@property (nonatomic, copy) NSString *scid;
// streamId
@property (nonatomic, copy) NSString *streamId;
// 调用截屏接口是否成功
@property (nonatomic) BOOL isCutScreenOk;
// 重新连接七牛sdk的次数
@property (nonatomic) int retryNumSDK;
// 重新连接开始直播接口的次数
@property (nonatomic) int retryNumForStartLive;
// 重新连接截图接口的次数
@property (nonatomic) int retryNumForCutScrene;
// 是否是最后一次截屏
@property (nonatomic) BOOL isLastCutScrene;
// 创建直播的枚举
@property (nonatomic) CreateVideoType createVideoType;

@property (nonatomic, assign) NSInteger intTimeJieTu;


@property (nonatomic, strong) Reachability *internetReachability;
@property (nonatomic, strong) UIView *sessionView;

// 准备直播view，view内包含写点啥textview
@property (nonatomic, strong) MPTReadyLiveView *readyLiveView;
// 控制view，包括控制闪光灯、摄像头翻转等等
@property (nonatomic, strong) MPTControlView *controlView;
// 调试view，包括调试摄像头，调整自己的位置等等
@property (nonatomic, strong) MPTDebugLiveView *debugView;
// 倒计时view，5、4、3、2、1倒计时页面
@property (nonatomic, strong) MPTLiveCountDownView *countDownView;
// 直播结束view
@property (nonatomic, strong) MPTLiveOverView *liveoverView;
// 直播登录view
@property (nonatomic, strong) MPTLiveLoginView *loginView;
// 申请内测资格view
@property (nonatomic, strong) MPTLiveApplyView *applyView;
// 申请内测资格页面结果view
@property (nonatomic, strong) MPTLiveApplyResultView *applyResultView;
// 聊天、点赞等交互view
@property (nonatomic, strong) MPTLiveIMActionView *actionIMView;
//
@property (nonatomic, copy) NSString *likeNum;
// 不去重复的人数
@property (nonatomic, copy) NSString *memberNum;
// 表示七牛sdk是否重新连接过 当七牛sdk因为断网重联而连接成功时不去请求req_StartLive接口
@property (nonatomic) BOOL isRetry;
//
@property (nonatomic, strong) NSDictionary *loginDic;

/// 分享图片的url
@property (nonatomic, strong) NSString *strCover;

/// 服务器给的分享图片
@property (nonatomic, strong) UIImage *imageShare;

// 滤镜类型
@property (nonatomic, strong) YXVideoEffectModel *effectModel;
// 滤镜相关参数
@property (nonatomic, strong) YXVideoEffect *effectVideo;

@property (nonatomic, strong) MBProgressHUD *hud;

/// 加人聊天室的id
@property (nonatomic, strong) NSString *chatroomId;

/// 断开连接时间
@property (nonatomic, strong) NSTimer *timeChiSu;

/// 七牛端断开次数
@property (nonatomic, assign) NSInteger QiNiuErrorCount;

/// 记录时间的
@property (nonatomic, assign) NSInteger intTimeNumber;

/// 七牛定时time的提示
@property (nonatomic, strong) UIAlertView *alertTime;

/// 七牛从连接的次数的提示
@property (nonatomic, strong) UIAlertView *alertQiNiu;

/// 封面
@property (nonatomic, strong) UIAlertView *alertFengMian;

/// 主播信息
@property (nonatomic, strong) NSDictionary *dicChannel;

/// 主播的控制台
@property (nonatomic, strong) MPTLiveKongZhiTaiView *viewKongZhiTai;

/// 选择的滤镜
@property (nonatomic, strong) NSString *strLujing;

@end


@implementation MPTLiveViewController {
    PLVideoStreamingConfiguration *_512kbps, *_256kbps, *_800kbps;
}


#pragma mark - ***************************** View Lifecycle ***********************************

- (void)viewDidLoad
{
    [super viewDidLoad];
    
    self.QiNiuErrorCount = 0;
    self.intTimeNumber = 0;
    
    self.intTimeJieTu = 2;
    // 默认将关闭前置摄像头
    self.cameraIsSelf = NO;
    
    self.internetReachability = [Reachability reachabilityForInternetConnection];
    [self.internetReachability startNotifier];
    
    // 网络状态监控
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(reachabilityChanged:)
                                                 name:kReachabilityChangedNotification
                                               object:nil];
    
    // app进入后台时发送的消息
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(appGoBg) name:@"appGoBg" object:nil];
    // 加入聊天室失败的消息,日后替换为delegate
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(joinChatRoomError) name:@"joinChatRoomError" object:nil];
    
    // 跳转消息
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(jumpVC)
                                                 name:@"jumpToNav0"
                                               object:nil];
    
    // 注册键盘显示和隐藏事件
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillShow:) name:UIKeyboardWillShowNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification object:nil];
    
    /// 直播中分享消息
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(ZhiBoZhongShare) name:@"ZhiBoZhongShare" object:nil];
    
    /// 仅分享图片的消息
       [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(zhiBoShareTuPian) name:@"ShareTuPian" object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(changeLvJingForNSNotification:) name:@"LuJing" object:nil];
    
    /// 后台回到前台开始推流
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(startTuiLiu:) name:@"startTuiLiu" object:nil];
    
    // 初始化subview
    [self initCustom];
    
    // 初始化七牛sdk
    [self initPLCameraStreamingSession:nil];
    
    // 初始化变量
    [self initVar];
}

- (BOOL)prefersStatusBarHidden
{
    return NO;
}

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
    
    [self.session destroy];
    self.session = nil;
    
    // 释放前置滤镜
    PixelControllerRelease();
}

/// 重阳哥让加的，我不知道是解决什么问题的
- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    [self.session startCaptureSession];
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    [[TPTabBarManager share] showBottomView:NO animation:YES];
    
}

- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [self.session stopCaptureSession];
}

#pragma mark - ***************************** Init All Views **********************************

/*!
 *  @author caixun, 15-12-08 19:12:19
 *
 *  @brief  初始化变量  目前该函数只是初始化滤镜
 *
 *  @since v1.0.4
 */
- (void)initVar
{
    // 初始化前置滤镜
    PixelControllerInit();
    
    self.effectVideo = [[YXVideoEffect alloc] initWithEditor:nil];
    self.effectVideo.discardClips = YES;
    
    PixelControllerLinkDisplayView(self.sessionView, PixelControllerDisplayViewFillModeAspectRatioAndFill);
    
    PixelControllerSetPassConfiguration(nil);
}

/**
 *  初始化view中相关的控件：导航栏
 *  判断用户是否具有直播权限
 */
- (void)initCustom
{
    // 隐藏导航栏，目前先放这，明天来了放到它该在的地方
    [[self navigationController] setNavigationBarHidden:YES animated:NO];
    
    /// 创建准备直播页面
    [self initReadyLiveView];
}

/**
 *  // 准备直播view，view内包含写点啥textview
 */
- (void)initReadyLiveView
{   
    // 准备直播view，view内包含写点啥textview
    self.readyLiveView = [[MPTReadyLiveView alloc] initWithFrame:self.view.frame];
    _readyLiveView.vc = self;
    [self.readyLiveView setTargetForBtn:self withStartAction:@selector(onClickForShowDebugLive:) withMyHomeAction:nil];
    [self.view addSubview:self.readyLiveView];
}

/**
 *  // 控制view，包括控制闪光灯、摄像头翻转等等
 */
- (void)initControlView
{
    // 控制view，包括控制闪光灯、摄像头翻转等等
    self.controlView = [[MPTControlView alloc] initWithFrame:CGRectMake(0, -64, screenW, 64)];
    [self.controlView setTargetForBtn:self withKongZhiTai:@selector(KongZhiTaiClicked:)];
}

/**
 *  // 调试view，包括调试摄像头，调整自己的位置等等
 */
- (void)initDebugView
{
    // 调试view，包括调试摄像头，调整自己的位置等等
    self.debugView = [[MPTDebugLiveView alloc] initWithFrame:self.view.frame];
    [self.debugView setTargetForBtn:self withStartAction:@selector(onClickForShowStartLive:)];
}

/**
 *  // 倒计时view，5、4、3、2、1倒计时页面
 */
- (void)initCountDownView
{
    // 倒计时view，5、4、3、2、1倒计时页面
    self.countDownView = [[MPTLiveCountDownView alloc] initWithFrame:self.view.frame];
    self.countDownView.delegate = self;
    self.countDownView.backgroundAlpha = 0.2;
    self.countDownView.countdownColor = [UIColor whiteColor];
    self.countDownView.countdownFrom = 3;
    self.countDownView.finishText = @"";
    self.countDownView.finishImgv = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"LiveCountDown"]];
    [self.countDownView updateAppearance];
}

/**
 *  // 直播结束view
 */
- (void)initLiveoverView
{
    /// 因为之前同事在别的吗view里给superVIew 添加了个 用户信息view， 有问题了，在这里移除
    NSArray *ary = [NSArray arrayWithArray:self.view.subviews];
    for (UIView *view in ary)
    {
        if ([view isKindOfClass:[MPTLiveAllUserInfoView class]])
        {
            [view removeFromSuperview];
        }
    }
    // 直播结束view
    self.liveoverView = [[MPTLiveOverView alloc] initWithFrame:self.view.frame];
    [self.liveoverView setTargetForBtn:self withGoonLiveAction:@selector(onClickForGoonLive:) withgoMyHomeAction:nil withCloseAction:@selector(onClickCloseForLiveOver:)];
    [self.liveoverView setViewContent:self.likeNum withMemberNum:self.memberNum];
}

/**
 *  创建聊天、点赞等交互view
 */
- (void)initActionIMView
{
    self.actionIMView = [[MPTLiveIMActionView alloc] initWithIsLive:CGRectMake(0, 64, screenW, screenH - 64) withFromLive:YES];
    self.actionIMView.isFromLive = YES;
    [self.actionIMView setUserInfo:[MPTLoginUser unArchiver].suid withNick:[MPTLoginUser unArchiver].nick withIcon:[MPTLoginUser unArchiver].icon];
    [self.actionIMView setStreamInfo:self.scid];
}


/**
 *  初始化直播sdk
 */
- (void)initPLCameraStreamingSession:(NSDictionary *)sdkDic
{
    self.sessionView = [[UIView alloc] initWithFrame:self.view.bounds];
    [self.view addSubview:self.sessionView];
    // 将sessionView推到最底层
    [self.view sendSubviewToBack:self.sessionView];
    
    PLStream *stream = [PLStream streamWithJSON:sdkDic];
    
    void (^permissionBlock)(void) = ^{
        
        // 视频编码配置
        _512kbps = [[PLVideoStreamingConfiguration alloc] initWithVideoSize:CGSizeMake(360, 656)
                                                             videoFrameRate:25
                                                   videoMaxKeyframeInterval:25
                                                               videoBitrate:512 * 1000
                                                          videoProfileLevel:AVVideoProfileLevelH264Baseline30];
        
        _256kbps = [[PLVideoStreamingConfiguration alloc] initWithVideoSize:CGSizeMake(360, 656)
                                                             videoFrameRate:20
                                                   videoMaxKeyframeInterval:20
                                                               videoBitrate:256 * 1000
                                                          videoProfileLevel:AVVideoProfileLevelH264Baseline30];
        
        _800kbps = [[PLVideoStreamingConfiguration alloc] initWithVideoSize:CGSizeMake(360, 656)
                                                             videoFrameRate:25
                                                   videoMaxKeyframeInterval:25
                                                               videoBitrate:800 * 1000
                                                          videoProfileLevel:AVVideoProfileLevelH264Baseline30];


        
        // 音频编码配置
        PLAudioStreamingConfiguration *audioConfiguration = [PLAudioStreamingConfiguration configurationWithAudioQuality:kPLAudioStreamingQualityHigh1];
        
        
        // 推流 session
        self.session = [[PLCameraStreamingSession alloc] initWithVideoConfiguration:_512kbps
                                                                 audioConfiguration:audioConfiguration
                                                                             stream:stream
                                                                   videoOrientation:AVCaptureVideoOrientationPortrait];
        self.session.delegate = self;
        //self.session.previewView = self.sessionView;
        self.session.bufferDelegate = self;
    };
    
    void (^noAccessBlock)(void) = ^{
        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(@"No Access", nil)
                                                            message:NSLocalizedString(@"!", nil)
                                                           delegate:nil
                                                  cancelButtonTitle:NSLocalizedString(@"Cancel", nil)
                                                  otherButtonTitles:nil];
        [alertView show];
    };
    
    switch ([PLCameraStreamingSession cameraAuthorizationStatus])
    {
        case PLAuthorizationStatusAuthorized:
            permissionBlock();
            break;
        case PLAuthorizationStatusNotDetermined:
        {
            [PLCameraStreamingSession requestCameraAccessWithCompletionHandler:^(BOOL granted)
             {
                 // 回调确保在主线程，可以安全对 UI 做操作
                 granted ? permissionBlock() : noAccessBlock();
             }];
        }
            break;
        default:
            noAccessBlock();
            break;
    }
}


#pragma mark - ****************************** Button Touch Event ********************************


/// 点击控制台按钮的事件
- (void)KongZhiTaiClicked:(UIButton *)sender
{
    if (!_viewKongZhiTai)
    {
        _viewKongZhiTai = [[MPTLiveKongZhiTaiView alloc] initWithFrame:CGRectMake(0, -105, screenW, 105)];
        [_viewKongZhiTai setTargetForBtn:self withGuanbi:@selector(onClickForClose:)];
        [_viewKongZhiTai setTargetForBtn:self withJingt:@selector(toggleCameraButtonPressed:)];
        [_viewKongZhiTai setTargetForBtn:self withSanGuanDeng:@selector(torchButtonPressed:)];
        [_viewKongZhiTai setTargetForBtn:self withJIngYin:@selector(muteButtonPressed:)];
        [_viewKongZhiTai setTargetForBtn:self withLvJing:@selector(ButtonLvJing:)];
        [self.view addSubview:_viewKongZhiTai];
    }
    else
    {
        [_viewKongZhiTai show];
    }
}

/**
 *  准备直播view，点击开始直播，显示调试页面
 *
 *  @param sender 点击按钮对象
 */
- (void)onClickForShowDebugLive:(id)sender
{
    if (_readyLiveView.imageFengMian == nil)
    {
        if (!_alertFengMian)
        {
            // 弹出提示框，让用户确认是否确定要结束直播
            _alertFengMian = [[UIAlertView alloc] initWithTitle:@"温馨提示" message:@"这是一个看脸的时代，上传最美封面才能开启直播"
                                                    delegate:self
                                           cancelButtonTitle:@"懂了"
                                           otherButtonTitles:nil];
            
            [_alertFengMian show];
        }
        else
        {
            [_alertFengMian show];
        }
        
        return;
    }
    
    // 将文本框中用户填写的内容存放到全局变量中，以备后续在直播结束页面中点击继续直播时使用
    MPTSingleObjectInstance.createVideoContent = [self.readyLiveView getTextViewValue];
    
    self.createVideoType = From_Ready;
    
    // 请求接口数据
    [self req_GetIMToken];
}

/**
 *  调试页面，点击开始直播按钮，显示倒计时view
 *
 *  @param sender 点击按钮对象
 */
- (void)onClickForShowStartLive:(id)sender
{
    
    /// 0 代表啥也没选
    
    /// 皮肤 记录选择的皮肤
    if (self.debugView.xiaIndex >= self.debugView.aryImages.count || self.debugView.xiaIndex < 0)
    {
        [MPTLiveIMManager sharedInstance].strPiFu = @"-1";
    }
    else
    {
        [MPTLiveIMManager sharedInstance].strPiFu = [NSString stringWithFormat:@"%ld",(long)self.debugView.xiaIndex];
    }
    
    /// 皮肤 记录选择的滤镜
    if (self.debugView.youIndex >= self.debugView.aryLuJing.count || self.debugView.youIndex < 0)
    {
        [MPTLiveIMManager sharedInstance].strLuJing = @"-1";
    }
    else
    {
        [MPTLiveIMManager sharedInstance].strLuJing = [NSString stringWithFormat:@"%ld",(long)self.debugView.xiaIndex];
    }
    
    [self.debugView removeFromSuperview];
    
    [self initControlView];
    [self.view addSubview:self.controlView];
    // 加载倒计时view
    [self initCountDownView];
    [self.view insertSubview:_countDownView belowSubview:_controlView];
    [self.countDownView start];
}

/**
 *  控制view，包括控制闪光灯、摄像头翻转等等，点击view上的关闭按钮，点击关闭按钮
 *
 *  @param sender 点击按钮对象
 */
- (void)onClickForClose:(id)sender
{
    // 弹出提示框，让用户确认是否确定要结束直播
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"确定结束直播吗?" message:@""
                                                   delegate:self
                                          cancelButtonTitle:@"取消"
                                          otherButtonTitles:@"确定", nil];
    
    [alert show];
}

/**
 *  直播结束view 点击关闭按钮
 *
 *  @param sender
 */
- (void)onClickCloseForLiveOver:(id)sender
{
    [self removeAllSubViews];
    
    [self initReadyLiveView];
    [self.view addSubview:self.readyLiveView];
}

/**
 *  直播结束view，点击继续直播按钮点击事件
 *
 *  @param sender
 */
- (void)onClickForGoonLive:(id)sender
{
    self.createVideoType = From_LiveOver;
    
    [self removeAllSubViews];
    
    // 加载倒计时view
    [self initControlView];
    [self.view addSubview:self.controlView];
    
    [self initCountDownView];
    [self.view insertSubview:self.countDownView belowSubview:self.controlView];
    
    // 请求接口数据
    [self req_CreateVideo];
}

/**
 *  旋转摄像头事件
 *
 *  @param sender 点击按钮对象
 */
- (void)toggleCameraButtonPressed:(id)sender
{
    [self.session toggleCamera];
    self.cameraIsSelf = !self.cameraIsSelf;
    if (self.cameraIsSelf) {
        self.sessionView.layer.affineTransform = CGAffineTransformMakeScale(-1, 1);
    } else {
        self.sessionView.layer.affineTransform = CGAffineTransformIdentity;
    }
}

/**
 *  摄像头 开/关 事件
 *
 *  @param sender 点击按钮对象
 */
- (void)torchButtonPressed:(id)sender
{
    UIButton *but = sender;
    but.selected = !but.selected;
    self.session.torchOn = !self.session.isTorchOn;
}

/**
 *  静音相关
 *
 *  @param sender 点击按钮对象
 */
- (void)muteButtonPressed:(id)sender
{
    UIButton *but = sender;
    but.selected = !but.selected;
    self.session.muted = !self.session.isMuted;
}

/**
 *  滤镜相关
 *
 *  @param sender 点击按钮对象
 */
- (void)ButtonLvJing:(id)sender
{
    UIButton *but = sender;
    if (!but.selected)
    {
        [self chooseLvJing:@""];
    }
    else
    {
        [self chooseLvJing:_strLujing];
    }
    but.selected = !but.selected;
}


#pragma mark - ****************************** Notification Handler ********************************

// 消息跳转逻辑
- (void)jumpVC
{
    [self dismissViewControllerAnimated:YES completion:^{
        
    }];
}

/// 只分享图片
- (void)zhiBoShareTuPian
{
    _actionIMView.allAudienceListView.headerView.butGuanBi.hidden = YES;
    _actionIMView.allAudienceListView.headerView.butShare.hidden = YES;
    
    /// 截取图像
    CGRect rect = _actionIMView.allAudienceListView.frame;
    UIGraphicsBeginImageContextWithOptions(rect.size, YES, 0.0);
    CGContextRef context = UIGraphicsGetCurrentContext();
    _actionIMView.allAudienceListView.layer.backgroundColor = [UIColor clearColor].CGColor;
    [_actionIMView.allAudienceListView.layer renderInContext:context];
    UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    
    _actionIMView.allAudienceListView.headerView.butGuanBi.hidden = NO;
    _actionIMView.allAudienceListView.headerView.butShare.hidden = NO;
    
    /// 分享对象
    MPTLiveWeiboAutoShare *weiboShare = [[MPTLiveWeiboAutoShare alloc]init];
    NSDictionary *paraDict = @{@"thumb":[MPTLoginUser unArchiver].icon,@"scid":[MPTSingleObjectInstance setStrDefValue:self.scid]};
    [weiboShare setShareInfo:paraDict];
    [weiboShare setLiveHeadInfo:[MPTLoginUser unArchiver].area withTitle:MPTSingleObjectInstance.createVideoContent];
    /// 分享截屏
    if (img)
    {
        [weiboShare sendWeiboWithScid:self.scid shareEnum:ZhiBoZhong image:img];
    }
    else
    {
        [weiboShare sendWeiboWithScid:self.scid shareEnum:ZhiBoZhong image:[UIImage imageNamed:@"shareMoRen"]];
    }
}

/// 直播中分享
- (void)ZhiBoZhongShare
{
    MPTChannelModel *modelZhuBo = [MPTChannelModel fromJSONDictionary:_dicChannel error:nil];
    
    NSString *liveString =  @"1";
    
//    //shareImage：分享出去的图片 isHost：是否是主播，0不是   1是主播     isLive：是否为直播 isLive为1   录播为0
    NSDictionary *weiboSharePara = @{@"shareImage":modelZhuBo.videoImage,@"isHost":liveString,@"model":modelZhuBo,@"isLive":liveString};
    
    MPTLiveShareView *  liveShareView= [[MPTLiveShareView alloc] initWithFrame:self.view.bounds];
    liveShareView.strShareUrl = [NSString stringWithFormat:@"http://www.miaopai.com/show/%@.htm", self.scid];
    [liveShareView initWithLiveChannel:weiboSharePara];
    [self.view addSubview:liveShareView];
    [self.view bringSubviewToFront:liveShareView];
}

- (void)reachabilityChanged:(NSNotification *)notif
{
    Reachability *curReach = [notif object];
    NSParameterAssert([curReach isKindOfClass:[Reachability class]]);
    NetworkStatus status = [curReach currentReachabilityStatus];
    
    if (NotReachable == status)
    {
        // 对断网情况做处理
        [self showTipMessage:@"当前网络不给力，请检查后再试"];
        
        UIImage *liveImg = [UIImage imageNamed:@"CountDownNoNet"];
        [self.controlView changeLiveImage:liveImg];
    }
    else
    {
        if(ReachableViaWWAN == status)
        {
            [self showTipMessage:@"正在使用2G/3G/4G，可能会产生网络流量"];
        }
        
        UIImage *liveImg = [UIImage imageNamed:@"CountDown"];
        [self.controlView changeLiveImage:liveImg];
    }
    
    NSLog(@"Networkt Status: %s", networkStatus[status]);
}

/**
 *  当app进入后台的时候，将直播结束
 */
- (void)appGoBg
{
    if (PLStreamStateConnected == self.session.streamState)
    {
        [self closeLiveForClick];
    }
}

- (void)joinChatRoomError
{
    // 显示播放结束页面
    [self closeLiveForClick];
}

- (void)keyboardWillShow:(NSNotification *)notification
{
//    NSDictionary *info = [notification userInfo];
//    NSValue *value = [info objectForKey:UIKeyboardFrameEndUserInfoKey];
//    CGSize keyboardSize = [value CGRectValue].size;
//    
//    [UIView beginAnimations:nil context:NULL];
//    [UIView setAnimationDuration:[[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue]];
//    CGRect frame = self.actionIMView.frame;
//    frame.origin.y = - keyboardSize.height;
//    self.actionIMView.frame = frame;
//    [UIView commitAnimations];
}

- (void)keyboardWillHide:(NSNotification *)notification
{
    /* Move the toolbar back to bottom of the screen */
//    NSDictionary *info = [notification userInfo];
//    [UIView beginAnimations:nil context:NULL];
//    [UIView setAnimationDuration:[[info objectForKey:UIKeyboardAnimationDurationUserInfoKey] floatValue]];
//    CGRect frame = self.actionIMView.frame;
//    frame.origin.y = 0;
//    self.actionIMView.frame = frame;
//    [UIView commitAnimations];
}

/// 开始推流的方法
- (void)startTuiLiu:(NSNotification *)notif
{
    [self startSession];
}

- (void)changeLvJingForNSNotification:(NSNotification *)notif
{
    if(notif.object == nil)
    {
        _strLujing = @"";
        [self chooseLvJing:@""];
        
        return ;
    }
    
    NSString *lvJingName = (NSString *)notif.object;
    _strLujing = lvJingName;
    [self chooseLvJing:lvJingName];
}


#pragma mark - ********************** PLCameraStreamingSessionDelegate *****************************

- (void)cameraStreamingSession:(PLCameraStreamingSession *)session streamStateDidChange:(PLStreamState)state
{
    if (PLStreamStateConnected == state)
    {
        if(self.liveoverView.superview != nil || self.readyLiveView.superview!=nil)
        {
            [self stopSession];
        }
    }
    else if(PLStreamStateDisconnected == state || PLStreamStateError == state)
    {
        // session重联的机制是：直播结束view没有显示出来并且开始直播接口请求失败次数没有超过最大值时，才会执行重练session操作
        if(self.liveoverView.superview == nil && self.retryNumForStartLive<=3 && self.readyLiveView.superview==nil)
        {
            self.isRetry = YES;
            // 如果不是用户点击关闭直播按钮，主要是断开了就重试重连
            if(self.retryNumSDK <=3)
            {
                dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                    [self startSession];
                });
            }
            else
            {
                [self performSelector:@selector(showTipMessage:) withObject:@"请确认您的网络是否畅通" afterDelay:0.1f];
                [self closeLiveForAuto];
            }
        }
    }
}

- (void)cameraStreamingSession:(PLCameraStreamingSession *)session didDisconnectWithError:(NSError *)error
{
    /// 记录错误次数
    _QiNiuErrorCount++;
    /// 开启定时器
    if (!_timeChiSu)
    {
        _timeChiSu = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(QiNiuErrorJishi) userInfo:nil repeats:YES];
    }
    
    if(self.liveoverView.superview == nil && self.retryNumForStartLive<=3 && self.readyLiveView.superview==nil)
    {
        self.isRetry = YES;
        // 如果不是用户点击关闭直播按钮，主要是断开了就重试重连
        if(self.retryNumSDK <=3)
        {
            dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
                [self startSession];
            });
        }
        else
        {
            if (!_alertQiNiu)
            {
                // 弹出提示框，让用户确认是否确定要结束直播
                _alertQiNiu = [[UIAlertView alloc] initWithTitle:@"直播网络状态不佳是否继续?" message:@""
                                                        delegate:self
                                               cancelButtonTitle:@"继续"
                                               otherButtonTitles:@"关闭", nil];
                
                [_alertQiNiu show];
            }
        }
    }
}

/// @abstract 获取到摄像头原数据时的回调, 便于开发者做滤镜等处理
- (CMSampleBufferRef)cameraStreamingSession:(PLCameraStreamingSession *)session
             cameraSourceDidGetSampleBuffer:(CMSampleBufferRef)sampleBuffer
{
    PixelControllerModifySampleBuffer(sampleBuffer);
    return sampleBuffer;
}

- (void)cameraStreamingSession:(PLCameraStreamingSession *)session pushedNoneAudioBuffer:(AudioBuffer *)buffer
{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        [MPTTips showTips:@"声音好像出了问题建议重新开启直播" duration:2.0f];
    });
}

#pragma mark - PL Sending buffer delegate 

static UInt64 sendingBufferEmptyCount = 0;

#define CHANGE_BITRATE_TIMEOUT_800 25 * 180
#define CHANGE_BITRATE_TIMEOUT_512 25 * 60

double MachTimeToSecs(uint64_t time)
{
    mach_timebase_info_data_t timebase;
    mach_timebase_info(&timebase);
    return (double)time * (double)timebase.numer /
    (double)timebase.denom /1e9;
}

uint64_t lastTime = 0;

void __print_time_info_(void *ins) {
    
    [MPTTips showTips:[NSString stringWithFormat:@"switch to %lukbps, fps %lu", (unsigned long)((__bridge MPTLiveViewController *)(ins)).session.videoConfiguration.videoBitRate / 1000, ((__bridge MPTLiveViewController *)(ins)).session.videoConfiguration.videoFrameRate] duration:2.0];
    
    uint64_t time = mach_absolute_time();
    if (lastTime) {
        NSLog(@"距离上次%f秒", MachTimeToSecs(time - lastTime));
    }
    lastTime = time;
}

#define USE_BITRATE_SUIT 1

- (void)streamingSessionSendingBufferDidEmpty:(id)session {
#if USE_BITRATE_SUIT
    if (++sendingBufferEmptyCount > CHANGE_BITRATE_TIMEOUT_800) {
        if (self.session.videoConfiguration != _800kbps) {
            self.session.videoConfiguration = _800kbps;
            __print_time_info_((__bridge void *)(self));
        }
    } else if (sendingBufferEmptyCount > CHANGE_BITRATE_TIMEOUT_512) {
        if (self.session.videoConfiguration != _512kbps) {
            self.session.videoConfiguration = _512kbps;
            __print_time_info_((__bridge void *)(self));
        }
    }
#endif
}

- (void)streamingSessionSendingBufferDidFull:(id)session {
#if USE_BITRATE_SUIT
    if (self.session.videoConfiguration != _256kbps) {
        self.session.videoConfiguration = _256kbps;
        __print_time_info_((__bridge void *)(self));
    }
    sendingBufferEmptyCount = 0;
#endif
}

#pragma mark - ********************** Delegate *****************************

- (void)countdownFinished:(MPTLiveCountDownView *)view
{
    [self.countDownView removeFromSuperview];
}

- (void)countdownValueToOne:(MPTLiveCountDownView *)view
{
    if(self.liveoverView.superview != nil || self.readyLiveView.superview!=nil)
    {
        return ;
    }
    
    // 启动计时器
    [self.controlView beginTime];
    
    // 将重联的次数置为0
    self.retryNumSDK = 0;
    self.isRetry = NO;
    
    // startSession会阻塞主线程，所以将其放进子线程中去
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        // 试图去建立直播链接
        if (PLStreamStateConnected == self.session.streamState)
        {
            // 这块在stop之后并没有再执行start，因为如果在执行stop之前session是链接状态的话，
            // 那么这块执行stop之后就会在session的状态回调函数中自动执行重新连接操作，
            // 因为在倒计时运行的时候结束直播(liveoverview)的superview肯定是nil
            [self stopSession];
        }
        else
        {
            [self startSession];
        }
    });
}

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if ([_alertFengMian isEqual:alertView])
    {
        return;
    }
    
    switch (buttonIndex)
    {
        case 0:
        {
            NSLog(@"Cancel Button Pressed");
            /// 清除七牛记录状态
            _intTimeNumber = 0;
            _QiNiuErrorCount = 0;
            break;
        }
        default:
        {
            if ([alertView isEqual:_alertQiNiu])
            {
                /// 七牛连接超过三次的逻辑
                [self closeLiveForAuto];
            }
            else
            {
                [self closeLiveForClick];
            }
            
            break;
        }
    }
}


#pragma mark - ****************************** Functions *********************************

- (void)QiNiuErrorJishi
{
    /// 时间
    _intTimeNumber++;
    if (_intTimeNumber >= 120)
    {
        if (_QiNiuErrorCount >=3)
        {
            if (!_alertTime)
            {
                // 弹出提示框，让用户确认是否确定要结束直播
                _alertTime = [[UIAlertView alloc] initWithTitle:@"直播网络状态不佳是否继续?" message:@""
                                                               delegate:self
                                                      cancelButtonTitle:@"继续"
                                                      otherButtonTitles:@"关闭", nil];
                
                [_alertTime show];
            }
        }
        else
        {
            _QiNiuErrorCount =0;
            _intTimeNumber = 0;
        }
    }
}

/// 获取通讯运营商
- (NSString *)getCarrier
{
    NSString * operatorName = @"";
    CTTelephonyNetworkInfo *info = [[CTTelephonyNetworkInfo alloc] init];
    CTCarrier *carrier = info.subscriberCellularProvider;
    
    if (carrier.carrierName)
    {
        operatorName = carrier.carrierName;
    }
    
    return operatorName;
}
/*!
 *  @author caixun, 15-12-08 19:12:51
 *
 *  @brief  切换滤镜函数
 *
 *  @param lvJingName 滤镜名字
 *
 *  @since v1.0.4
 */
- (void)chooseLvJing:(NSString *)lvJingName
{
    if([@"" isEqualToString:lvJingName])
    {
        PixelControllerSetPassConfiguration(nil);
        
        return ;
    }
    
    NSString *bundlePath = [[NSBundle mainBundle] pathForResource:@"Theme" ofType:@"bundle"];
    self.effectModel = [[YXVideoEffectModel alloc] initWithName:lvJingName andPath:bundlePath];
    
    NSArray *config = [self.effectVideo applyEffectByConfig:self.effectModel.getEffectArray withDir:self.effectModel.getEffectDirPath];
    PixelControllerSetPassConfiguration(config);
}

/// 直播前分享使用
- (void)shareZhiBoQian
{
    MPTLiveWeiboAutoShare *weiboShare = [[MPTLiveWeiboAutoShare alloc]init];
    
    NSDictionary *paraDict = @{@"thumb":[MPTLoginUser unArchiver].icon,@"scid":[MPTSingleObjectInstance setStrDefValue:self.scid]};
    [weiboShare setShareInfo:paraDict];
    
    [weiboShare setLiveHeadInfo:[MPTLoginUser unArchiver].area withTitle:MPTSingleObjectInstance.createVideoContent];
    
    if (_debugView.isShare)
    {
        /// 直播前分享
        [weiboShare sendWeiboWithScid:self.scid shareEnum:ZhiBoQian image:nil];
    }
}

- (void)stopSession
{
    PixelControllerEndCrop();
    [self.session stop];
}

/// 七牛链接回调
- (void)startSession
{
    [[AVAudioSession sharedInstance] setActive:YES error:nil];
    PixelControllerBeginCrop();
    [self.session startWithCompleted:^(BOOL success)
    {
        if (success)
        {
//            NSLog(@"Publish URL: %@", self.session.pushURL.absoluteString);
            
            if(self.liveoverView.superview != nil || self.readyLiveView.superview!=nil)
            {
                return ;
            }
            self.retryNumSDK = 0;
            self.retryNumForStartLive = 0;
            if(self.isRetry == NO)
            {
                // 初始化imview
                [self initActionIMView];
                // 加入聊天室
                [self.actionIMView joinChatRoom:_chatroomId];
                [self.view insertSubview:self.actionIMView belowSubview:self.controlView];
                [self req_StartLive];
            }
        }
        else
        {
            self.retryNumSDK++;
        }
    }];
}

/**
 *  清除view上所有的自定义view
 */
- (void)removeAllSubViews
{
    [NSObject cancelPreviousPerformRequestsWithTarget:self];
    
    [self.readyLiveView removeFromSuperview];
    
    [self.controlView removeFromSuperview];
    
    [self.debugView removeFromSuperview];
    
    [self.countDownView stop];
    [self.countDownView removeFromSuperview];
    self.countDownView = nil;
    
    [self.liveoverView removeFromSuperview];
    
    [self.loginView removeFromSuperview];
    
    [self.applyView removeFromSuperview];
    
    [self.applyResultView removeFromSuperview];
    
    [self.actionIMView removeFromSuperview];
    self.actionIMView = nil;
    
    [_viewKongZhiTai removeFromSuperview];
    _viewKongZhiTai = nil;
}

/**
 *  当重联超过链接次数的时候执行该函数
 */
- (void)closeLiveForAuto
{
    /// 清除七牛记录状态
    _intTimeNumber = 0;
    _QiNiuErrorCount = 0;
    
    self.session.torchOn = NO;
    
    [self removeAllSubViews];
    
    [self initLiveoverView];
    [self.view addSubview:self.liveoverView];
        
    if(self.isCutScreenOk == NO)
    {
        self.isLastCutScrene = YES;
        [self req_LiveState];
    }
    [self req_FinishLive];
}

/**
 *  当开始直播接口重新连接超过最大重练次数之后调用此函数
 */
- (void)showReadyLiveViewForAuto
{
    self.session.torchOn = NO;
    
    // 结束推流
    [self stopSession];
    
    [self removeAllSubViews];
    [self initReadyLiveView];
    [self.view addSubview:self.readyLiveView];
}

- (void)showTipMessage:(NSString *)errorMes
{
    [MPTTips showTips:errorMes duration:1.0f];
}

/**
 *  为了在onClickForClose函数中添加alertview，所以才添加次函数
 */
- (void)closeLiveForClick
{
    /// 清空七牛记录信息
    _intTimeNumber = 0;
    _QiNiuErrorCount = 0;
    
    /// 记录人数和赞数
//    self.likeNum = [_actionIMView getLikeNum];
//    self.memberNum = [_actionIMView getUsersNum];
    
    // 给观看端发送停止直播的消息
    [self.actionIMView sendCloseLiveMessage];
    
    self.session.torchOn = NO;
    
    [self removeAllSubViews];
    
    // 这块估计需要添加UIAlertView,后续再说
    if (PLStreamStateConnected == self.session.streamState)
    {
        // 点击关闭按钮进入直播结束页面
        [self initLiveoverView];
        [self.view addSubview:self.liveoverView];
        
        // 是否已经成功截图
        if(self.isCutScreenOk == NO)
        {
            // 如果没有成功截图，那么需要在此时去调用截图接口
            self.isLastCutScrene = YES;
            [self req_LiveState];
        }
        // 调用直播结束接口 告知后台直播已经结束
        [self req_FinishLive];
        
        // 结束推流
        [self stopSession];
    }
    else
    {
        // 点击关闭按钮进入准备直播页面
        [self initReadyLiveView];
        [self.view addSubview:self.readyLiveView];
    }
}

- (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)newSize
{
    UIGraphicsBeginImageContextWithOptions(newSize, NO, 0.0);
    [image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
    UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return newImage;
}


#pragma mark - ********************** Net Connection Event *****************************

/**
 *  创建视频接口，用户写点啥页面中点击开始直播按钮时需要请求的接口
 */
- (void)req_CreateVideo
{
    // 清空上一次的直播过程中的点赞和观看人数
    self.likeNum = @"0";
    self.memberNum = @"0";
    
    NSString *deviceName = [[UIDevice alloc] hardwareDescription];//获取机型
    NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    // 设别型号，运营商，网络状态
    NSString *strDeviceName = [NSString stringWithFormat:@"%@system%@_%@_%@_version%@",
                               ZB_Str_Protect(deviceName),
                               ZB_Str_Protect([[UIDevice currentDevice] systemVersion]),
                               ZB_Str_Protect([self getCarrier]),
                               ZB_Str_Protect(networkStat()),
                               ZB_Str_Protect(version)];
    
    
    NSString *locationText = @"";
    if(![@"nil" isEqualToString:MPTSingleObjectInstance.currentLocation])
    {
        locationText = MPTSingleObjectInstance.currentLocation;
    }
    NSString *str = [NSString stringWithFormat:@"%f,%f",MPTSingleObjectInstance.currentlatitude,MPTSingleObjectInstance.currentLongitude];
    NSDictionary *paraDic = @{
                              @"status":@"2",
                              @"title":(MPTSingleObjectInstance.createVideoContent == nil ? @"" : MPTSingleObjectInstance.createVideoContent),
                              @"width":@"",
                              @"height":@"",
                              @"islive":@"1",
                              @"os":@"ios",
                              @"locationText":(locationText == nil ? @"" :locationText),
                              @"location":(str == nil ? @"": str),
                              @"device_name":strDeviceName
                              };
    [[MPTHttpClient sharedMPHTTPClient] postPath:@"open/video/create.json" parameters:paraDic timeoutInterval:15 queuePriority:NSOperationQueuePriorityNormal cacheRequest:NO success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         [_hud hide:YES];
         [_hud removeFromSuperview];
         
         if([responseObject isKindOfClass:[NSDictionary class]])
         {
             NSDictionary *liveStreamDic = [responseObject objectForKey:@"liveStream"];
             
             if (liveStreamDic == nil || liveStreamDic.allKeys.count ==0)
             {
                  [MPTTips showTips:@"获取信息失败请从新获取" duration:1.0f];
                 return ;
             }
             self.scid = [responseObject objectForKey:@"scid"];
             self.streamId = [liveStreamDic objectForKey:@"id"];
             
             if(self.createVideoType == From_Ready)
             {
                 /// 根据是否选取封面进行判断是否上传图片
                 if (_readyLiveView.imageFengMian)
                 {
                     [self reqPostImage];
                 }
                 
                 // 显示调试页面(debugView)
                 [self.readyLiveView removeFromSuperview];
                 
                 [self initDebugView];
                 [self.view addSubview:self.debugView];
                 
                 
             }
             else
             {
                 [self.countDownView start];
             }
             
             PLStream *stream = [PLStream streamWithJSON:liveStreamDic];
             self.session.stream = stream;
             
             _chatroomId = [NSString stringWithFormat:@"%@",[responseObject objectForKey:@"chatroomId"]];
         }
     }
     failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         [_hud hide:YES];
         [_hud removeFromSuperview];
         [MPTTips showTips:@"当前网络连接差，请重试" duration:1.0f];
         
         [self showReadyLiveViewForAuto];
     }
     cached:^(NSDictionary *cachedObject)
     {
         
     }];
}

/**
 *  录制真正开始时请求接口
 */
- (void)req_StartLive
{
    
    NSMutableDictionary *paraDic = [@{
                              @"scid":[MPTSingleObjectInstance setStrDefValue:self.scid],
                              @"streamId":[MPTSingleObjectInstance setStrDefValue:self.streamId]
                              } mutableCopy];
    /// 皮肤参数
    [paraDic setValue:@([[MPTLiveIMManager sharedInstance].strPiFu integerValue] + 1) forKey:@"skin"];
    
    [[MPTHttpClient sharedMPHTTPClient] getPath:@"m/startLive.json" parameters:paraDic queuePriority:NSOperationQueuePriorityNormal cacheRequest:NO success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         if(self.liveoverView.superview != nil || self.readyLiveView.superview!=nil)
         {
             return ;
         }
         
         /// 发送phus
         [self reqPush];
         
         NSArray *chatUsersArray = responseObject[@"result"][@"chatroomUsers"];
         /// 观众数量
         NSNumber *number = responseObject[@"result"][@"rcnt"];
         [self.actionIMView setLiveAllUserDataSource:[NSMutableArray arrayWithArray:chatUsersArray] userNumber:number];
         
         self.isCutScreenOk = NO;
         self.retryNumForCutScrene = 0;
         self.isLastCutScrene = NO;
         
         /// 请求视频状态
         [self req_LiveState];
//         [self performSelector:@selector(req_LiveState) withObject:nil afterDelay:2.0f];
     }
     failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         if(self.liveoverView.superview != nil || self.readyLiveView.superview!=nil)
         {
             return ;
         }
         
         if(self.retryNumForStartLive <= 3)
         {
             [self performSelector:@selector(req_StartLive) withObject:nil afterDelay:1.0f];
             self.retryNumForStartLive ++;
         }
         else
         {
             [MPTTips showTips:@"请检查您的网络是否畅通" duration:1.0f];
             
             [self showReadyLiveViewForAuto];
         }
     }
     cached:^(NSDictionary *cachedObject)
     {
         
     }];
}

- (void)req_LiveState
{
     NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
    NSDictionary *paraDic;
    _intTimeJieTu = _intTimeJieTu + 2;
    paraDic = @{
                @"scid":[MPTSingleObjectInstance setStrDefValue:self.scid],
                @"streamId":[MPTSingleObjectInstance setStrDefValue:self.streamId],
                @"snapshot":@"1",
                @"seconds":@(_intTimeJieTu),
                @"version":ZB_Str_Protect(version)
                };
    
    [[MPTHttpClient sharedMPHTTPClient] getPath:@"m/statusLive.json" parameters:paraDic queuePriority:NSOperationQueuePriorityNormal cacheRequest:NO success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         if(self.liveoverView.superview != nil || self.readyLiveView.superview!=nil)
         {
             return ;
         }
         
         if ([responseObject isKindOfClass:[NSDictionary class]])
         {
             NSDictionary *dic = [NSDictionary dictionaryWithDictionary:responseObject];
             
             /// 获取主播信息
             self.dicChannel = dic[@"result"][@"channel"];
             
             /// 这个时候结束直播
             if ([dic[@"result"][@"status"]integerValue] == 2 && [dic[@"result"][@"liveStatus"]integerValue] == 2)
             {
                 [self closeLiveForClick];
             }

             self.strCover = dic[@"result"][@"cover"];
             
             if (self.isCutScreenOk == YES)
             {
                 /// 分享成功过
                 if ([dic[@"result"][@"rcnt"] integerValue] > 0)
                 {
                     ///给主播同步数据 （观众台位置）
                     [_actionIMView setUserNumber:dic[@"result"][@"rcnt"]];
                    
                     /// 发送同步赞数与人数的消息的判断 （主播发送同步人数的消息给秒拍端）
                     if ([dic[@"result"][@"mcnt"] integerValue] > 0)
                     {
                         [_actionIMView postUsersNumberInForMPT:dic[@"result"][@"rcnt"]
                                                      LikeCount:dic[@"result"][@"mcnt"]];
                     }
                 }
                 
                 /// 结束直播时候使用的人数
                 if ([[_actionIMView getUsersNum] integerValue] < [dic[@"result"][@"ucnt"] integerValue])
                 {
                     [_actionIMView setUsersNumber:[dic[@"result"][@"ucnt"] integerValue]];
                 }
                 
                 /// 赞数同步
//                 if ([dic[@"result"][@"mcnt"] integerValue] > 0)
//                 {
//                     [_actionIMView setLikeNumber:dic[@"result"][@"mcnt"]];
//                 }
                 
                 [self performSelector:@selector(req_LiveState) withObject:nil afterDelay:60.0f];
             }
             else
             {
                 /// 没有分享过
                 if (![self.strCover isEqualToString:@""] && self.strCover != nil)
                 {
                     // 此时可以去做分享操作
                     /// 开始分享
                     [self shareZhiBoQian];
                     [self performSelector:@selector(req_LiveState) withObject:nil afterDelay:60.0f];
                     self.isCutScreenOk = YES;
                 }
                 else
                 {
                     [self performSelector:@selector(req_LiveState) withObject:nil afterDelay:4.0f];
                     
                     // 这个_intTimeJieTu == 10这个逻辑不是蔡勋写的（看着蔡勋他写的）
                     if(_intTimeJieTu == 10)
                     {
                         // 已经第三次失败了
                         [self shareZhiBoQian];
                         self.isCutScreenOk = YES;
                     }
                 }
             }
             
             
             /// 处理im开关问题
             if (![responseObject[@"result"][@"imShow"] integerValue])
             {
                 _actionIMView.hidden = YES;
             }
         }
     }
     failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         if(self.liveoverView.superview != nil || self.readyLiveView.superview!=nil)
         {
             return ;
         }
         [self performSelector:@selector(req_LiveState) withObject:nil afterDelay:4.0f];
     }
     cached:^(NSDictionary *cachedObject)
     {
         
     }];
}

/**
 *  直播结束时调用的接口
 */
- (void)req_FinishLive
{
    NSDictionary *paraDic = @{
                              @"scid":[MPTSingleObjectInstance setStrDefValue:self.scid],
                              @"streamId":[MPTSingleObjectInstance setStrDefValue:self.streamId]
                              };
    [[MPTHttpClient sharedMPHTTPClient] getPath:@"m/finishLive.json" parameters:paraDic queuePriority:NSOperationQueuePriorityNormal cacheRequest:NO success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         
     }
     failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {

     }
     cached:^(NSDictionary *cachedObject)
     {
         
     }];
}

/**
 *  获取im唯一表示token
 */
- (void)req_GetIMToken
{
     [[RCIMClient sharedRCIMClient] logout];
    
    _hud = [[MBProgressHUD alloc] initWithFrame:self.view.bounds];
    _hud.labelText = @"正在初始化视频...";
    [self.view addSubview:_hud];
    [_hud show:YES];
    NSString *imToken = [[NSUserDefaults standardUserDefaults] objectForKey:@"IMToken"];
    if(imToken != nil)
    {
        [[RCIMClient sharedRCIMClient] connectWithToken:imToken success:^(NSString *userId)
         {
             NSLog(@"Connect 成功");
             
             dispatch_async(dispatch_get_main_queue(), ^{
                 [self req_CreateVideo];
             });
         }
         error:^(RCConnectErrorCode status)
         {
             // Connect 失败
             NSLog(@"Connect 失败");
             dispatch_async(dispatch_get_main_queue(), ^{
                 [_hud hide:YES];
                 [_hud removeFromSuperview];
             });
             [self performSelector:@selector(showTipMessage:) withObject:@"请确认您的网络是否畅通" afterDelay:0.1f];
         }
         tokenIncorrect:^()
         {
             // Token 失效的状态处理
             NSLog(@"Connect 失效的状态处理");
             dispatch_async(dispatch_get_main_queue(), ^{
                 [_hud hide:YES];
                 [_hud removeFromSuperview];
             });
             [self performSelector:@selector(showTipMessage:) withObject:@"请确认您的网络是否畅通" afterDelay:0.1f];
         }];
        
        return ;
    }
    
    [[MPTHttpClient sharedMPHTTPClient] getPath:@"m/getImToken.json" parameters:nil timeoutInterval:15  queuePriority:NSOperationQueuePriorityNormal cacheRequest:NO success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         NSDictionary *result = [responseObject objectForKey:@"result"];
         NSString *token = [result objectForKey:@"imToken"];
         
         if(token!=nil)
         {
             [[NSUserDefaults standardUserDefaults] setValue:token forKey:@"IMToken"];
         }
         
         [[RCIMClient sharedRCIMClient] connectWithToken:token success:^(NSString *userId)
          {
              NSLog(@"Connect 成功");
              
              dispatch_async(dispatch_get_main_queue(), ^{
                  [self req_CreateVideo];
              });
          }
          error:^(RCConnectErrorCode status)
          {
              // Connect 失败
              NSLog(@"Connect 失败");
              dispatch_async(dispatch_get_main_queue(), ^{
                  [_hud hide:YES];
                  [_hud removeFromSuperview];
              });
              [self performSelector:@selector(showTipMessage:) withObject:@"请确认您的网络是否畅通" afterDelay:0.1f];
          }
          tokenIncorrect:^()
          {
              // Token 失效的状态处理
              NSLog(@"Connect 失效的状态处理");
              dispatch_async(dispatch_get_main_queue(), ^{
                  [_hud hide:YES];
                  [_hud removeFromSuperview];
              });
              [self performSelector:@selector(showTipMessage:) withObject:@"请确认您的网络是否畅通" afterDelay:0.1f];
          }];
     }
     failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         dispatch_async(dispatch_get_main_queue(), ^{
             [_hud hide:YES];
             [_hud removeFromSuperview];
         });
         [self performSelector:@selector(showTipMessage:) withObject:@"请确认您的网络是否畅通" afterDelay:0.1f];
     }
     cached:^(NSDictionary *cachedObject)
     {
         
     }];
}

/**
 *  往服务器端上报点赞数量
 */
- (void)req_UploadLikeNum
{
    if(self.liveoverView.superview != nil || self.readyLiveView.superview!=nil || self.session.isRunning == NO)
    {
        [NSObject cancelPreviousPerformRequestsWithTarget:self];
        
        return ;
    }
    
    // 获取当前点赞数量
    NSString *likeNum = [self.actionIMView getLikeNum];
    
    NSDictionary *paraDic = @{
                              @"scid":[MPTSingleObjectInstance setStrDefValue:self.scid],
                              @"streamId":[MPTSingleObjectInstance setStrDefValue:self.streamId],
                              @"snapshot":@"1",
                              @"mcnt":[MPTSingleObjectInstance setStrDefValue:likeNum]
                              };
    [[MPTHttpClient sharedMPHTTPClient] getPath:@"m/statusLive.json" parameters:paraDic queuePriority:NSOperationQueuePriorityNormal cacheRequest:NO success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         NSDictionary *resultDic = [responseObject objectForKey:@"result"];
         self.likeNum = [[resultDic objectForKey:@"mcnt"] description];
         self.memberNum = [[resultDic objectForKey:@"ucnt"] description];
         
         [self performSelector:@selector(req_UploadLikeNum) withObject:nil afterDelay:6];
     }
     failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
         [self performSelector:@selector(req_UploadLikeNum) withObject:nil afterDelay:6];
     }
     cached:^(NSDictionary *cachedObject)
     {
         
     }];
}

/// 上传图片
- (void)reqPostImage
{
    ///
    _readyLiveView.imageFengMian = [self imageWithImage: _readyLiveView.imageFengMian scaledToSize:CGSizeMake(480, 480)];
    
    /// 封面
    NSData *data_imageFengMian = UIImageJPEGRepresentation(_readyLiveView.imageFengMian,0.5);
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    
    
    if (self.scid)
    {
        [parameters setValue:self.scid forKey:@"scid"];
        NSString *version = [[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleShortVersionString"];
        [parameters setValue:ZB_Str_Protect(version) forKey:@"version"];
    }
    
    if([MPTConfig sharedConfig].userToken)
    {
        [parameters setValue:[MPTConfig sharedConfig].userToken forKey:@"token"];
    }
    AFHTTPRequestOperationManager *manager = [AFHTTPRequestOperationManager manager];
    
    [manager POST:@"http://api.miaopai.com/m/uploadLiveCover.json" parameters:parameters constructingBodyWithBlock:^(id<AFMultipartFormData> formData) {
        /// 封面图
        if (data_imageFengMian) {
            [formData appendPartWithFileData:data_imageFengMian name:@"cover" fileName:@"cover.jpg" mimeType:@"image/jpeg"];
        }
        
    } success:^(AFHTTPRequestOperation *operation, id responseObject) {
        
        NSLog(@"封面图片上传%@",responseObject);
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
        
    }];
}

/// 发生push的接口
- (void)reqPush
{
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setValue:[MPTConfig sharedConfig].userToken forKey:@"token"];
    [parameters setValue:self.scid forKey:@"scid"];
    
    [[MPTHttpClient sharedMPHTTPClient] getPath:@"m/publishLivePush.json" parameters:parameters queuePriority:NSOperationQueuePriorityNormal cacheRequest:NO success:^(AFHTTPRequestOperation *operation, id responseObject)
     {
         NSLog(@"phus成功");
     }
                                        failure:^(AFHTTPRequestOperation *operation, NSError *error)
     {
          NSLog(@"phus失败");
     }
                                         cached:nil];
}

@end
